package org.he.auth.interceptor;

import org.he.auth.vo.LoginVO;
import org.he.basic.annotation.HePermission;
import org.he.basic.data.ContextMap;
import org.he.org.domain.Employee;
import org.he.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

/**
 * @author He
 * @date 2023/12/5  17:36
 * 这个类是用于做 权限拦截的
 * 权限: 认证 和 鉴权
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private IEmployeeService employeeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // false代表拦截,true代表放行
        System.out.println("拦截器开始工作...............");
        // 获取前端的token 从header中获取请求
        String token = request.getHeader("token");
        if (Objects.isNull(token)) {
            // 没有token说明没有登录,应该拦截
            response.getWriter().print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        // 根据token获取map中的对象
        Employee employee = ContextMap.loginMap.get(token);
        System.out.println(employee);
        if (Objects.isNull(employee)) {
            // map中的对象为空的话,说明token不正确,应该拦截
            response.getWriter().print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        // 鉴权
        // 1.判断访问资源是否需要权限 - 判断请求的方法是否有权限注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        HePermission annotation = method.getAnnotation(HePermission.class);
        if (Objects.nonNull(annotation)) {
            // 2.如果需要权限
            // 3.获取用户权限
            // 根据用户id 查询 角色id 再查 角色拥有的权限
            List<String> permissions = employeeService.queryPermissionsById(employee.getId());
            System.out.println(permissions);
            // 4.获取资源权限 方法名+controller名
            String name = method.getName(); // 方法名
            String simpleName = method.getDeclaringClass().getSimpleName(); // controller名
            String resourceUrl = simpleName + ":" + name;
            System.out.println(resourceUrl);
            // 5.判断用户权限是够包含资源权限
            boolean contains = permissions.contains(resourceUrl.trim());
            if (!contains) {
                response.getWriter().print("{\"success\":false,\"msg\":\"noPermission\"}");
                return false;
            }
        }
        return true;
    }
}
